/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.biz.front.controller.ChannelController.java
 * <p>
 * 类产生时间: 2014/3/27 21:12
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.econsole.modules.weixin.controller;

import com.alibaba.fastjson.JSON;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.modules.api.v2.service.IProjectService;
import com.oceansoft.mobile.econsole.modules.api.v2.service.IProjectYyService;
import com.oceansoft.mobile.econsole.modules.ascproject.entity.ProjectInfo;
import com.oceansoft.mobile.econsole.modules.ascproject.entity.YyProjectEntity;
import com.oceansoft.mobile.econsole.modules.base.controller.BaseController;
import com.oceansoft.mobile.econsole.modules.base.entity.ApiPager;
import com.oceansoft.mobile.econsole.modules.base.entity.Pager;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.member.entity.WtMember;
import com.oceansoft.mobile.econsole.modules.member.service.IMemberService;
import com.oceansoft.mobile.econsole.modules.member.service.IWtMemberService;
import com.oceansoft.mobile.econsole.modules.weixin.config.WxFactory;
import com.oceansoft.mobile.econsole.modules.weixin.entity.DeptBase;
import com.oceansoft.mobile.econsole.modules.weixin.entity.OrderTime;
import com.oceansoft.mobile.econsole.modules.weixin.entity.Wxjq;
import com.oceansoft.mobile.econsole.modules.weixin.service.IApiWxjqService;
import com.oceansoft.mobile.econsole.weixin.api.OauthAPI;
import com.oceansoft.mobile.econsole.weixin.api.enums.OauthScope;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;

/**
 * @author Administrator
 */
@Controller
@RequestMapping("api/police")
public class PoliceFrontController extends BaseController {
    @Resource
    private IApiWxjqService wxService;
    @Resource
    IProjectService projectService;
    @Resource
    IProjectYyService projectYyService;
    @Resource
    IMemberService memberService;
    @Resource
    IWtMemberService wtMemberService;

    /**
     * 办事指南
     *
     * @return
     */
    @RequestMapping(value = "catalogs", method = RequestMethod.GET)
    public String catalogs() {
        return "mobile/police/work-catalogs";
    }

    @RequestMapping("item_center")
    public String gotoItemCenter() {
        return "weixin/item/item_center";
    }

    @RequestMapping("item_detail")
    public String gotoItemDetail() {
        return "weixin/item/item_detail";
    }

    /**
     * 部门职能介绍 DepartIntro
     *
     * @return
     */
    @RequestMapping(value = "departIntro", method = RequestMethod.GET)
    public String departIntro() {
        return "mobile/police/work-departIntro";
    }

    /**
     * 跳转到部门办事事项
     *
     * @param id    警钟的id
     * @param model
     * @return
     */
    @RequestMapping(value = "SMatter", method = RequestMethod.GET)
    public String gotoSMatterList(
            @RequestParam(value = "id", required = true) String id, Model model) {
        model.addAttribute("sid", id);
        // 市局为1
        model.addAttribute("bureaus", -1);
        return "mobile/police/work-SMatter";
    }

    /**
     * 跳转到部门办事事项（分局的）
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "FMatter", method = RequestMethod.GET)
    public String gotoFMatterList(
            @RequestParam(value = "id", required = true) String id, Model model) {
        // 分局的ID
        model.addAttribute("fid", id);
        // 分局为2
        model.addAttribute("bureaus", 2);
        return "mobile/police/work-SMatter";
    }

    /**
     * 查询事项详细信息
     *
     * @param dept_type
     * @param dept_id
     * @param matterId
     * @param model
     * @return
     */
    @RequestMapping(value = "matters", method = RequestMethod.GET)
    public String gotoMatters(@RequestParam("dept_type") String dept_type,
                              @RequestParam("dept_id") String dept_id,
                              @RequestParam("matterId") String matterId, Model model) {
        if (dept_id.equals("-1")) {
            dept_id = "1";
        }
        model.addAttribute("dept_type", dept_type);
        model.addAttribute("dept_id", dept_id);
        model.addAttribute("matterId", matterId);
        return "mobile/police/work-SMatterDetail";
    }

    /*
     * 微信集群类别选择
     *
     * @return
     */
    @RequestMapping(value = "gotoWechat", method = RequestMethod.GET)
    public String gotoWxjq() {
        return "mobile/police/wxjq-catalogs";
    }

    /**
     * 区县微信公众平台
     *
     * @return
     */
    @RequestMapping(value = "wechatAccounts", method = RequestMethod.GET)
    public String DistrictWb(HttpServletRequest request, Model model) {
        String title = request.getParameter("title");
//		int pageindex = Integer.parseInt(request.getParameter("pageindex"));
        String areaId = request.getParameter("areaId");
        String type = request.getParameter("type");

        List<Wxjq> wxjqList = wxService.getWxjqList(title, areaId, type);
//		Pager<Wxjq> page = wxService.queryWxjq2(title, pageindex,areaId);
//		Pager<Wxjq> page = wxService.queryWxjq(title, pageindex);

        model.addAttribute("wxjqList", wxjqList);
//		model.addAttribute("page",page);
        model.addAttribute("areaId", areaId);
        model.addAttribute("type", type);

        return "mobile/police/wechatAccounts";
    }

    @RequestMapping(value = "wechatAccountsQuery", method = RequestMethod.GET)
    @ResponseBody
    public String wechatAccountsQuery(HttpServletRequest request, Model model) {
        String title = request.getParameter("title");
        String areaId = request.getParameter("areaId");
        String type = request.getParameter("type");
        List<Wxjq> wxjqList = wxService.getWxjqList(title, areaId, type);
        JSONArray json = new JSONArray();
        for (Wxjq wxjz : wxjqList) {
            JSONObject jo = new JSONObject();
            jo.put("url", wxjz.getUrl());
            jo.put("icon", wxjz.getIcon());
            jo.put("title", wxjz.getTitle());
            json.add(jo);
        }
        String result = json.toString();
        return result;
    }

    /**
     * 区县微信公众平台
     *
     * @return
     */
    @RequestMapping(value = "DistrictWb2", method = RequestMethod.GET)
    @ResponseBody
    public Object DistrictWb2(HttpServletRequest request, Model model) {
        String _title = request.getParameter("title");
        String areaId = request.getParameter("areaId");
        String title = "";
        try {
            title = URLDecoder.decode(_title, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        int pageindex = Integer.parseInt(request.getParameter("pageindex"));
//		Pager<Wxjq> page = wxService.queryWxjq(title, pageindex);
        Pager<Wxjq> page = wxService.queryWxjq2(title, pageindex, areaId);
        JSONObject json = JSONObject.fromObject(page);
        return json.toString();
    }

    /**
     * 违章查询
     *
     * @return
     */
    @RequestMapping(value = "gotoWZCX", method = RequestMethod.GET)
    public String gotoWZCX() {
        return "mobile/police/work-WZCX";
    }
//

    /**
     * 违章查询结果
     *
     * @return
     */
    @RequestMapping(value = "gotoWZCXInfo", method = RequestMethod.GET)
    public String gotoWZCXInfo(Model model, HttpServletRequest request) throws Exception {
        String caridone = request.getParameter("CarId_one");

        if (StringUtils.isNotEmpty(caridone))
            caridone = URLDecoder.decode(caridone, "utf-8");

        model.addAttribute("CarId_one", caridone);
        model.addAttribute("CarId_two", request.getParameter("CarId_two"));
        model.addAttribute("drive_license", request.getParameter("drive_license"));
        model.addAttribute("fn", request.getParameter("fn"));
        model.addAttribute("carordriver", request.getParameter("carordriver"));
        return "mobile/police/work-WZCXInfo";
    }

    @RequestMapping(value = "WZCXDetail", method = RequestMethod.GET)
    public String WZCXDetail(@RequestParam("data") String data, Model model) throws Exception {
        model.addAttribute("data", URLDecoder.decode(data, "utf-8"));
        return "mobile/police/work-WZCXDetail";
    }

    /**
     * 实时路况
     *
     * @return
     */
    @RequestMapping(value = "gotoSSLK", method = RequestMethod.GET)
    public String gotoSSLK() {
        return "mobile/police/SSLK";
    }


    /**
     * 预约详情
     *
     * @return
     */
    @RequestMapping(value = "order_detail/{prjguid}/{projectBillid}", method = RequestMethod.GET)
    public String gotoOrderDetail(@PathVariable("prjguid") String prjguid, @PathVariable("projectBillid") String projectBillid, HttpServletRequest request, Model model) {
        ProjectInfo projectInfo = projectService.getPrjInfo(projectBillid);
        YyProjectEntity yyPrjInfo = projectYyService.getYyPrjInfo(prjguid);

        if (null != projectInfo) {
            model.addAttribute("projectInfo", projectInfo);
        } else {
            model.addAttribute("projectInfo", new ProjectInfo());
        }
        if (null != yyPrjInfo) {
            if (yyPrjInfo.getNetProjectType().equals("4") || yyPrjInfo.getNetProjectType().equals("6")) {
                yyPrjInfo.setNetProjectType("大庆公安APP");
            } else if (yyPrjInfo.getNetProjectType().equals("5")) {
                yyPrjInfo.setNetProjectType("大庆公安微信公众号");
            } else if (yyPrjInfo.getNetProjectType().equals("2")) {
                yyPrjInfo.setNetProjectType("大庆公安网厅");
            } else {
                yyPrjInfo.setNetProjectType("大庆公安");
            }
            model.addAttribute("yyPrjInfo", yyPrjInfo);
        } else {
            model.addAttribute("yyPrjInfo", new YyProjectEntity());
        }

        String userGuid = request.getParameter("userGuid");
        if (com.oceansoft.mobile.econsole.common.util.StringUtils.isBlank(userGuid)) {
            WtMember member = getWxMemberSession();
            model.addAttribute("loginId", member.getUserName());
            model.addAttribute("userName", member.getAliasName());
        } else {
            WtMember member = wtMemberService.getWtMemberByUserGuid(userGuid);
            model.addAttribute("loginId", member.getUserName());
            model.addAttribute("userName", member.getAliasName());
        }
        model.addAttribute("projectBillid", projectBillid);


        return "weixin/order/order_detail";
    }

    /**
     * 我要预约
     *
     * @return
     */
    @RequestMapping("order_index")
    public String gotoOderPerson(Model model,HttpServletRequest request) {
        String matid = request.getParameter("matid");//事项编号
        model.addAttribute("matid", matid);
        String matname = request.getParameter("matname");//事项名称
        model.addAttribute("matname", matname);
        //微信端guid=0 APP有GUID  电话号码
        String guid = request.getParameter("guid");
        if("0".equals(guid)){
            if (null == getWxMemberSession()) {
                OauthAPI oauthAPI = WxFactory.buildOauthAPI();
                return "redirect:" + oauthAPI.getOauthPageUrl(WxFactory.PERCENTER_OAUTH_URL, OauthScope.SNSAPI_BASE, "123");
            }
            guid = getWxMemberSession().getTelephone();
        }

        model.addAttribute("guid", guid);
        Result r = this.getRegion("370600");
        model.addAttribute("region", r);//获取烟台市区域信息
        //通过区域获得部门
        List<DeptBase> list = (List<DeptBase>) r.getData();
        String qxid = "no";
        String dsid = "no";
        if (list.size() > 0) {
            qxid = list.get(0).getRegioncode();
            dsid = list.get(0).getParentcode();
        }
        Result rs = this.getDeptByRegin(matid, qxid, dsid, "1000");
        model.addAttribute("dept", rs.getData());

        ApiPager pager = (ApiPager) rs.getData();
        String deptid = "";
        if (pager.getList().size() > 0) {
            DeptBase deptbase = JSON.parseObject(pager.getList().get(0).toString(), DeptBase.class);
            deptid = deptbase.getGuid();
        }
        //通过事项编号和部门GUID获得 该部门当前事项的预约信息
        String res = "";
        try {
            res = HttpClientUtil.doGet(configInfo.getServiceInterfaceAddress() + "/reservation/ordermain/" + deptid + "/" + matid);
            // res = HttpClientUtil.doGet("http://zwfw.ytga.gov.cn/api/reservation/ordermain/"+deptid+"/"+matid);
        } catch (IOException e) {
            e.printStackTrace();
        }
        com.alibaba.fastjson.JSONObject object = JSON.parseObject(res);
        //获得预约部门时间
        if(null==object){
            model.addAttribute("time", "0");
        }else {
            OrderTime orderTime = JSON.parseObject(object.getString("data"), OrderTime.class);
            if (orderTime.getDays().size() > 0) {
                model.addAttribute("time", orderTime.getDays());
            }
        }
        return "weixin/order/order_person";
    }

    @RequestMapping("order_company")
    public String gotoOrderCompany() {
        return "weixin/order/order_company";
    }



    @ResponseBody
    @RequestMapping(value = "getOrderTime", method = RequestMethod.POST)
    public Result geteOrderTime(HttpServletRequest request){
        String deptid=request.getParameter("deptid");
        String  matid=request.getParameter("matid");


        String res= "";
        try {
            res = HttpClientUtil.doGet(configInfo.getServiceInterfaceAddress()+"/reservation/ordermain/"+deptid+"/"+matid);
//            res = HttpClientUtil.doGet("http://zwfw.ytga.gov.cn/api/reservation/ordermain/"+deptid+"/"+matid);
        } catch (IOException e) {
            e.printStackTrace();
        }
        com.alibaba.fastjson.JSONObject object = JSON.parseObject(res);
        //获得预约部门时间
        OrderTime orderTime=JSON.parseObject(object.getString("data"), OrderTime.class);

         if(orderTime.getDays().size()>0){
            return new Result(Result.SUCC,orderTime.getDays());
        }else{
            return new Result(Result.SUCC,"0","");
         }

    }

    @ResponseBody
    @RequestMapping(value = "orderinfo",method = RequestMethod.POST)
    public Result orderInfo(HttpServletRequest request){
        String deptid=request.getParameter("deptid");
        String deptname=request.getParameter("deptname");
        String matid=request.getParameter("matid");
        String matname=request.getParameter("matname");
        String timeid=request.getParameter("timeid");
        String orderday=request.getParameter("orderday");
        String start=request.getParameter("start");
        String end=request.getParameter("end");
        String creator=request.getParameter("creator");
        String res= HttpClientUtil.doPostString(configInfo.getServiceInterfaceAddress()+"/reservation/orderinfonocode",new HashMap<String, String>() {{
           put("deptid", deptid);
            put("deptname", deptname);
            put("matname", matname);
           put("timeid", timeid);
            put("matid", matid);
           put("orderday", orderday);
            put("start", start);
            put("end", end);
            put("creator", creator);
        }});
        com.alibaba.fastjson.JSONObject object= JSON.parseObject(res);
        if("false".equals(object.getString("succ"))){
        return new Result(Result.FAILURE,object.getString("res"));
        }
        return new Result(Result.SUCC,object.getString("data"),"");
    }

    @ResponseBody
    @RequestMapping(value = "getdepts", method = RequestMethod.GET)
    public Result getDepts(HttpServletRequest request){
        String matid=request.getParameter("matid");
        String qxid=request.getParameter("qxid");
        return this.getDeptByRegin(matid,qxid,"","1000");
    }

    @RequestMapping("myorder")
    public String gotoMyOrder(ModelMap model, HttpServletRequest request) {
        WtMember wtMember = getWxMemberSession() == null ? super.getMemberByGUid(request.getParameter("userGuid")) : getWxMemberSession();
        model.addAttribute("member", wtMember);
        return "weixin/order/myorder";
    }


    /**
     * 预约详情
     * @param orderId
     * @return
     */
    @RequestMapping(value = "orderDetail/{orderId}")
    public String getOrderDetail(@PathVariable("orderId") String orderId, ModelMap modelMap) {
        Result result = projectService.queryOrderDetail(orderId);
        modelMap.addAttribute("projectInfo",result.getData());
        return "weixin/order/order_detail";
    }

    /**
     * 撤销预约
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "revoke/{orderId}")
    public Result revokeMyOrder(@PathVariable("orderId") String orderId) {
        Result result = projectService.revoke(orderId);
//        Result result = new Result(200, "c0898b28-3326-47f3-b8b7-31cbf9a729ae");
        return result;

    }


}